﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace GMusicBox
{
    class ColorPicker : Control
    {
        public ColorPicker()
        {
            this.DoubleBuffered = true;
            Color0 = Color.White;
            Color1 = Color.Black;
        }

        Point mousePoint = new Point(-1, -1);
        public Color Color0 { get; set; }
        public Color Color1 { get; set; }
        public event EventHandler ColorChanged;

        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            if (mousePoint.X != -1 && mousePoint.Y != -1)
            {
                ColorDialog cd = new ColorDialog();
                bool color0 = e.X < this.Width / 2;
                cd.Color = color0 ? Color0 : Color1;

                if (cd.ShowDialog() == DialogResult.OK)
                {
                    if (color0) Color0 = cd.Color;
                    else Color1 = cd.Color;

                    if (ColorChanged != null) ColorChanged(this, EventArgs.Empty);
                }

                this.Invalidate();
                cd.Dispose();
            }
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            mousePoint = e.Location;
            this.Invalidate();
        }

        protected override void OnMouseLeave(EventArgs e)
        {
            base.OnMouseLeave(e);
            mousePoint = new Point(-1, -1);
            this.Invalidate();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            e.Graphics.FillRectangle(new LinearGradientBrush(this.ClientRectangle, Color0, Color1, LinearGradientMode.Horizontal), this.ClientRectangle);
            if (mousePoint.X != -1 && mousePoint.Y != -1)
            {
                if (mousePoint.X >= this.Width / 2) e.Graphics.FillRectangle(new SolidBrush(Color1), new Rectangle(this.Width / 2, 0, this.Width / 2, this.Height));
                else e.Graphics.FillRectangle(new SolidBrush(Color0), new Rectangle(0, 0, this.Width / 2, this.Height));
            }

            e.Graphics.DrawRectangle(Pens.Gray, new Rectangle(0, 0, this.Width - 1, this.Height - 1));
        }
    }
}
